# -*- coding: utf-8 -*-
import logging
import os
import signal
import socket
import threading
import time

from taskflow.engines.worker_based import worker
from multidelivery.db import api as db_api


logging.basicConfig(level=logging.INFO)
LOG = logging.getLogger(__name__)


class Worker(worker.Worker):

    def __init__(self, exchange, topic, tasks, hostname=None, **kwargs):

        if not hostname:
            hostname = socket.gethostname()
        self.hostname = hostname
        self._keepalive_evt = threading.Event()

        # use greenlet executor
        # if 'executor' not in kwargs:
        #     self.executor = futurist.GreenThreadPoolExecutor(max_workers=1000)
        #     kwargs['executor'] = self.executor
        self.register_signal()
        self._start = False
        self._topic = topic + '.' + self.hostname
        super(Worker, self).__init__(exchange, self._topic, tasks, **kwargs)

    def _init_host(self):
        db_api.create_worker(self.hostname)

    def _graceful_shutdown(self, *args):
        self.stop()

    @staticmethod
    def _fast_exit(*args):
        os._exit(1)

    def register_signal(self):
        signal.signal(signal.SIGINT, self._fast_exit)
        signal.signal(signal.SIGTERM, self._graceful_shutdown)

    def db_register_worker(self, hostname):
        while self._start:
            db_api.update_worker_heartbeat(self.hostname)
            time.sleep(10)

    def start(self):
        self._start = True

        self._init_host()
        self._executor.submit(self.run)
        self.wait()
        LOG.debug("Service Worker Started!")
        self.db_register_worker(self.hostname)

    def stop(self):
        super(Worker, self).stop()
        self._start = False


